#include <QPixmap>
#include <QPainter>
#include <QFontMetrics>

#include "sidebutton.h"

#include <QDebug>

#define SideButtonLeft          (10)
#define SideButtonIcon          (17)
#define SideButtonIconMargin    (3)

SideButton::SideButton(Direction direction, QWidget *parent):
    QAbstractButton(parent),
    m_content(QPixmap()),
    m_direction(direction),
    m_contentLeft(SideButtonLeft),
    m_contentTop(SideButtonIconMargin),
    m_isHover(false)
{
    //Set properties.
    setAutoFillBackground(true);
    setCheckable(true);
    //Update the button size.
    if(m_direction == North)
    {
        //Set the fixed height.
        setFixedHeight(SideButtonHeight);
    }
    else
    {
        //Set the fixed width.
        setFixedWidth(SideButtonHeight);
    }
}

void SideButton::setContent(const QPixmap &icon, const QString &text)
{
    //Prepare the content pixmap.
    QFont textFont = font();
    textFont.setPointSize(8);
    //Update the font.
    QRect textSize = QFontMetrics(textFont).boundingRect(text);
    //Rerender the content.
    m_content = QPixmap(textSize.width() + 1 + SideButtonIcon,
                        SideButtonIcon);    
    m_content.fill(QColor(0, 0, 0, 0));
    //Render the content.
    QPainter painter(&m_content);
    painter.fillRect(rect(), QColor(0, 0, 0, 0));
    painter.drawPixmap(3, 3, icon.scaled(11, 11, Qt::IgnoreAspectRatio,
                                         Qt::SmoothTransformation));
    painter.drawText(QPointF(1 + SideButtonIcon, 13),
                     text);
    painter.end();
    // Based on the direction, update the other size.
    if(m_direction == North)
    {
        //Just update the size.
        setFixedWidth(m_content.width() + (SideButtonLeft << 1));
    }
    else
    {
        // Change the left and top.
        m_contentLeft = SideButtonIconMargin;
        m_contentTop = SideButtonLeft;
        // Update the height.
        setFixedHeight(m_content.width() + (SideButtonLeft << 1));
        // Rotate the image.
        QTransform transform;
        transform.rotate((m_direction == West) ? 270 : 90);
        // Rotate left.
        m_content = m_content.transformed(transform);
    }
}

void SideButton::enterEvent(QEvent *)
{
    m_isHover = true;
    update();
}

void SideButton::leaveEvent(QEvent *)
{
    m_isHover = false;
    update();
}

void SideButton::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e)
    // Render the button using the content.
    QPainter painter(this);
    if(isChecked())
    {
        painter.fillRect(rect(), QColor(189, 189, 189));
    }
    else
    {
        if(m_isHover)
        {
            painter.fillRect(rect(), QColor(217, 217, 217));
        }
    }
    // Render the content.
    painter.drawPixmap(m_contentLeft, m_contentTop, m_content);
}
